import { getRequest } from '../../../api/baseRequest'

export default {
  props: {},
  data() {
    return {
      // 总投票数
      totalVote: 0, // 投票详情
      //旧的投票详情
      oldVoteList: [{}],
      //计算后的投票详情
      voteList: []
    }
  },
  watch: {
    // 投票数改变
    voteList: {
      handler(newVal, oldVal) {
        this.totalVote = newVal.reduce((total, item) => {
          return total + item.quantity
        }, 0)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // 查询投票详情 设计模式下不查询
    if (this.$attrs.mode === 'design') return
    if (this.item.config.showVoteResult) {
      this.getVoteList()
    }
  },
  methods: {
    getVoteList() {
      getRequest('/form/ext/getVoteCount', {
        formKey: this.$route.params.key,
        formItemId: this.item.formItemId
      }).then((res) => {
        this.oldVoteList = res.data
        this.voteList = this.oldVoteList
      })
    },
    /**
     * 单选
     * @param value
     */
    handleVote(value) {
      let voteList = JSON.parse(JSON.stringify(this.oldVoteList))
      // 查找
      let index = this.oldVoteList.findIndex((item) => value == item.value)
      if (index === -1) {
        if (value !== '') {
          voteList.push({
            value,
            quantity: 1
          })
        }
      } else {
        voteList[index].quantity++
      }
      this.voteList = voteList
    },
    handleArrayVote(value) {
      let voteList = JSON.parse(JSON.stringify(this.oldVoteList))
      // 查找
      value.forEach((v) => {
        let index = this.oldVoteList.findIndex((item) => v == item.value)
        if (index === -1) {
          voteList.push({
            value: v,
            quantity: 1
          })
        } else {
          voteList[index].quantity++
        }
        this.voteList = voteList
      })
    }
  }
}
